package com.cu.simpleerp.frame;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 数据库连接池配置
 * 其实和xml配置bean sqlSessionFactory差不多，也是通过配置DataSource,然后配置SqlSessionFactory
 */
@Configuration
public class JdbcConnectionConfiguration {

    @Autowired
    private Environment env;

    /**
     * 自定义数据库连接原获取
     * 默认是通过jdbc连接，改用连接池
     *
     * @return
     */
    @Bean
    public DataSource getDataSource() {
        Properties properties = new Properties();
        try {
            properties.put("driverClassName", env.getProperty("jdbc.datasource.driver-class-name"));
            properties.put("username", env.getProperty("jdbc.datasource.username"));
            properties.put("url", env.getProperty("jdbc.datasource.url"));
            properties.put("password", env.getProperty("jdbc.datasource.password"));
            return DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * mybatis的sqlSessionFactory 实例生成
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory getSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(getDataSource());
        sqlSessionFactory.setTypeAliasesPackage(env.getProperty("mybatis.type-aliases-package"));
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));
        return sqlSessionFactory.getObject();
    }
}
